<script setup lang="ts">
import { computed, onMounted, shallowRef } from "vue";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import ByIcon from "@/components/ui/ByIcon.vue";
import BySquare from "@/components/ui/BySquare.vue";

import useFetch from "@/hooks/useFetch";
import useMerchant from "@/stores/merchant";
import ApiMerchant from "@/api/merchant";
import { parseQueryString } from "@/utils";

import Icon1 from "@/static/images/merchant_menu_manage.png";
import Icon4 from "@/static/images/merchant_menu_setting.png";
import Icon2 from "@/static/images/merchant_menu_computer.png";
// import Icon3 from "@/static/images/merchant_menu_statistic.png";

import { TMerchantStaff } from "@/global";

const { params } = useRouter();

const { source } = defineProps<{
  source: TMerchantStaff;
}>();

const store = useMerchant();

const list = [
  {
    title: "扫码核销",
    fonticon: "Scan",
    type: "scan",
  },
  {
    title: "活动数据",
    icon: Icon1,
    path: "/packageMerchant/pages/activity/list?mid=" + source?.merchant_id,
    roleType: 1,
  },
  {
    title: "人员管理",
    icon: Icon4,
    path: "/packageMerchant/pages/staff/list?mid=" + source?.merchant_id,
    roleType: 1,
  },
  // {
  //   title: "销售数据",
  //   icon: Icon3,
  //   path: "/packageMerchant/pages/sale/list?mid=" + source?.merchant_id,
  // },
  {
    title: "品牌设置",
    icon: Icon2,
    path: "",
    roleType: 1,
  },
];

// 缓存最近 通过路由参数核销的 sn
const lastWriteOffParam = shallowRef<any>();

// 处理核销结果
async function handleVerifyResult(errMsg?: string) {
  const { confirm } = await Taro.showModal({
    title: `核销${!errMsg ? "成功" : "失败"}`,
    content: errMsg || "",
    confirmText: "继续核销",
    cancelText: "完成",
  });

  if (confirm) handleScan();
}

// 核销接口
const { run: submitVerify } = useFetch(
  ApiMerchant.verifyTicketCoupon,
  {
    immediate: false,
    showLoading: true,
    onSuccess: () => handleVerifyResult(),
    onError: (err) => handleVerifyResult(err.msg),
    onFinally: () => Taro.hideLoading(),
  },
  { hiddenToast: true }
);

/**
 * 核销 入口
 * @param sn 核销码
 * @param isAppShow 是否微信扫码形式
 */
function writeOffRequest(sn?: string, isAppShow?: boolean) {
  if (!sn) return;

  if (isAppShow) {
    lastWriteOffParam.value = params;
  }

  submitVerify({
    sn,
    merchant_id: store.merchantId,
  });
}

// 扫码操作
async function handleScan() {
  let { result } = await Taro.scanCode({});
  console.log("扫码结果", result);

  if (result.startsWith("http")) {
    let queryStr = decodeURIComponent(
      result.split("?")[1]?.replace("cq=", "") || ""
    );
    result = parseQueryString<{ sn: string }>(queryStr)?.sn;
  }

  writeOffRequest(result);
}

// 约等于onLounch
onMounted(() => {
  writeOffRequest(params.sn, true);
});

useDidShow(() => {
  // scene 1167是通过H5URL进入小程序的场景值
  // console.log("getLaunchOptionsSync", Taro.getLaunchOptionsSync());
  console.log("useDidShow", params);
  if (lastWriteOffParam.value !== params) {
    console.log("允许核销");
    writeOffRequest(params.sn, true);
  } else {
    console.log("已核销");
  }
});

// 跳转到子页面
function goTo({ type, path }: (typeof list)[number]) {
  if (type === "scan") handleScan();
  else if (!!path) Taro.navigateTo({ url: path });
  else Taro.showToast({ title: "尽请期待", icon: "none" });
}

/**
 * 当前登录员工的角色类型
 * 1 管理员 2 店长(未启用) 3 店员
 */
const staffType = computed(() => store.merchantStaff?.staff_type);
</script>

<template>
  <view class="flex justify-around">
    <template v-for="(item, index) in list" :key="index">
      <view
        class="flex-none"
        v-if="!item.roleType || item.roleType == staffType"
        @tap="goTo(item)"
      >
        <BySquare class="bg-white" :size="100">
          <ByIcon
            v-if="item.fonticon"
            class="text-primary"
            :size="36"
            :name="item.fonticon"
          />
          <image v-else class="w-[52px]" mode="widthFix" :src="item.icon" />
        </BySquare>

        <view class="mt-1 text-white text-sm">{{ item.title }}</view>
      </view>
    </template>
  </view>
</template>
